package com.ruoyi.web.controller.webContent;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONAware;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ExceptionUtil;
import com.ruoyi.framework.web.domain.server.Sys;
import com.ruoyi.system.domain.SysDictData;
import com.ruoyi.system.utils.DictUtils;
import com.ruoyi.web.controller.tool.*;
import com.ruoyi.webContent.domain.PlCalculateResult;
import com.ruoyi.webContent.domain.PlMatchType;
import com.ruoyi.webContent.domain.PlTeam;
import com.ruoyi.webContent.service.IPlCalculateResultService;
import com.ruoyi.webContent.service.IPlMatchTypeService;
import com.ruoyi.webContent.service.IPlTeamService;
import org.apache.commons.collections.ListUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 动态页面数据功能Controller
 *
 * @author ruoyi
 * @date 2020-05-07
 */
@Controller
@RequestMapping("/webContent/plBest")
public class PlContentController extends BaseController {

    public static void main(String[] args) throws Exception{
        JSONObject teamId_gameId = new JSONObject();
        JSONPath.set(teamId_gameId,"ldj.2002_2022","123456");
        System.out.println(teamId_gameId.toString());


    }

    protected final Logger logger = LoggerFactory.getLogger(PlContentController.class);

    public void getAllMatch(String gameName) {
        //获取所有网站数据
        List<SysDictData> pl_host = DictUtils.getDictCache("pl_rest_url");
        //获取游戏信息数据
        SysDictData gameDict = PlDataMakeBestUtils.getGameDictByGameName(gameName);
        //获取时间设置
        String today = DateUtils.getDate();
        String tomorrow = DateUtils.getNextDay(new Date());
        List<String> dateList = new ArrayList<>();
        dateList.add(today);
        dateList.add(tomorrow);
        //获取所有网站所有比赛
        Class<PlGetDataUtils> plGetDataUtilsClass = PlGetDataUtils.class;
        for (SysDictData host : pl_host) {
            try {
                logger.info("游戏名称："+gameDict.getDictLabel()+"；网站："+host.getRemark()+";获取所有比赛>>>开始！！！");
                Method getAllMatchM = plGetDataUtilsClass.getMethod("get_"+host.getDictLabel()+"_allMatch", String.class, List.class);
                JSONArray allMatchData = (JSONArray)getAllMatchM.invoke(plGetDataUtilsClass.newInstance(),gameDict.getDictLabel(), dateList);
                if(allMatchData.size()>0){
                    PlDataSetUtils.setHostgameAllMatch(host.getDictLabel(),gameName,allMatchData);
                }
                logger.info("游戏名称："+gameDict.getDictLabel()+"；网站："+host.getRemark()+";获取所有比赛>>>完成！！！获取数量："+allMatchData.size());
            }catch (Exception e){
                logger.error("获取所有比赛异常！！！网站："+host.getRemark()+"错误信息："+ExceptionUtil.getExceptionMessage(e));
            }
        }
        //另开线程来进行获取所有比赛的后续计算
        ExecutorService singleThreadExecutor = Executors.newFixedThreadPool(1);
        singleThreadExecutor.execute(new Runnable() {
            @Override
            public void run() {
                logger.info(gameName+"_获取所有比赛的后续计算>>>开始！！！");
                PlDataMakeBestUtils.allMatchDataMake(gameName);
                logger.info(gameName+"_获取所有比赛的后续计算>>>完成！！！");
            }
        });
    }


    /**
     * 定时任务获取所有比赛详情
     * @gameName 游戏名称
     */
    public void getAllContentQuartz(String gameName) throws NoSuchMethodException {
        List<SysDictData> pl_host = DictUtils.getDictCache("pl_rest_url");
        //梳理出需要获取的比赛信息
        JSONObject hostABsm = PlDataSetUtils.getGameHostABSameMatch(gameName);
        if(hostABsm==null){
            return;
        }
        //使用多线程来获取所有网站的需要的比赛信息
        ExecutorService singleThreadExecutor = Executors.newFixedThreadPool(10);
        //获取反射类
        Class<PlGetDataUtils> plGetDataUtilsClass = PlGetDataUtils.class;
        for (SysDictData host : pl_host) {
            //获取反射方法
            Method getAllMatchM = plGetDataUtilsClass.getDeclaredMethod("get_"+host.getDictLabel()+"_content", String.class);
            List<String> match_ids = (List<String>) JSONPath.read(hostABsm.toJSONString(), "$.."+host.getDictLabel());
            singleThreadExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    JSONObject host_contents = new JSONObject();
                    logger.info(gameName+"_"+host.getRemark()+"获取比赛详情>>>开始！！！");
                    for (String matchId:match_ids) {
                        //若已经获取了，则不去重复获取
                        if(host_contents.get(matchId)!=null){
                            continue;
                        }
                        try {
                            JSONObject content = (JSONObject)getAllMatchM.invoke(plGetDataUtilsClass.newInstance(),matchId);
                            host_contents.put(matchId,content);
                        }catch (Exception e){
                            logger.error(gameName+"_"+host.getRemark()+"matchId="+matchId+"获取比赛详情异常!!!报错信息："+ ExceptionUtil.getExceptionMessage(e));
                        }
                    }
                    PlDataSetUtils.setHostgameAllContent(host.getDictLabel(),gameName,host_contents);
                    logger.info(gameName+"_"+host.getRemark()+"获取比赛详情>>>完成！！！获取数量"+host_contents.size());
                }
            });
        }
        singleThreadExecutor.shutdown();
    }

    @GetMapping("/getpl")
    @ResponseBody
    public void getpl() {
        //赔率类型数据初始化
        PlDataMakeBestUtils.getPlMatchTypes("0",true);

        IPlCalculateResultService iPlCalculateResultService = (IPlCalculateResultService) ApplicationContextUtil.getBean("plCalculateResultServiceImpl");
        ExecutorService singleThreadExecutor = Executors.newFixedThreadPool(10);
        List<SysDictData> game_name_arr = DictUtils.getDictCache("game_name_arr");
        for (SysDictData game : game_name_arr) {
            singleThreadExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    //计算
                    logger.info(game.getDictLabel()+"_比赛详情封装和赔率计算>>>开始！！！");
                    List<PlCalculateResult> all_result = PlDataMakeBestUtils.getCalRes(game);
                    logger.info(game.getDictLabel()+"_比赛详情封装和赔率计算>>>结束！！！");
                    iPlCalculateResultService.insertPlCalculateResultList(game.getDictValue(),all_result);
                    logger.info(game.getDictLabel()+"_赔率计算结果存入数据库>>>完成！！！");
                    //发送邮件
                    PlRestController sended = (PlRestController)ApplicationContextUtil.getBean("plRestController");
                    if(all_result!=null){
                        sended.sendEmail(2L);
                        sended.sendEmail(3L);
                        logger.info(game.getDictLabel()+"_邮件发送功能>>>完成！！！（若无正赔率则不会发送）");
                    }

                }
            });
        }
    }
}
